<template>
  <div  style="width: 100%; height: 100%;">
    <div id="container" ref="container" style="width: 100%; height: 100%;" />
     <el-button size="mini" class="tool-button" @click="openDistanceTool">测距</el-button>
      <div style="margin-left:20px;margin-top:20px">
        <el-button size="mini" style="width: 190px; top: 200px;right: 500px;position: absolute;z-index: 99;" >经纬度{{ lng }}, {{ lat }}</el-button>
      </div>
   <el-dialog

      :visible.sync="dialogVisible"
      width="40%"
    >
      <el-card class="card-container" shadow="never">
        <el-form ref="tableForm" :inline="true" :model="drawPoint" label-width="125px" size="small">
          <el-form-item label="图形ID：" prop="rectangleId">
            <el-input v-model="drawPoint.rectangleId" placeholder="请输入图形ID" style="width: 350px;" maxlength="32" />
          </el-form-item>
          <el-form-item label="形状类型：">
            <el-select v-model="drawPoint.polygonType" placeholder="请选择" clearable class="form-width" style="width: 350px;">
              <el-option
                v-for="item in type"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属路段：" prop="roadId">
            <el-select v-model="drawPoint.roadId" placeholder="所属路段" clearable class="form-width" style="width: 350px;" filterable>
              <el-option
                v-for="item in roadList"
                :key="item.roadId"
                :label="item.name"
                :value="item.roadId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="方向：" prop="directionId">
            <el-select v-model="drawPoint.directionId" placeholder="请选择" clearable class="form-width" style="width: 350px;">
              <el-option
                v-for="item in dirList"
                :key="item.directionId"
                :label="item.name"
                :value="item.directionId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开始桩号：" prop="startStub">
            <el-input v-model="drawPoint.startStub" placeholder="请输入开始桩号" style="width: 350px;" maxlength="15" type="number" />
          </el-form-item>
          <el-form-item label="结束桩号：" prop="endStub">
            <el-input v-model="drawPoint.endStub" placeholder="请输入结束桩号" style="width: 350px;" type="number" maxlength="10" />
          </el-form-item>
          <el-form-item label="当前经度：">
            <el-input v-model="drawPoint.currentLon" placeholder="请输入当前经度" style="width: 350px;" />
          </el-form-item>
          <el-form-item label="当前纬度：">
            <el-input v-model="drawPoint.currentLat" placeholder="请输入当前纬度" style="width: 350px;" />
          </el-form-item>
          <el-form-item label="点：">
            <el-input v-model="drawPoint.polygon" placeholder="请输入点" style="width: 350px;" />
          </el-form-item>
        </el-form>
        </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" size="small" @click="handleDialogConfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import { getLatlonList, getLatlonSave } from '@/api/home/map/index'
export default {
  data () {
    return {
      map: '',
      polygons: [],
      lng: '',
      lat: '',
      rectangleInfo: {
        directionId: '1',
        roadId: '0001100151'
      },
      drawPoint: {
        currentLat: null,
        currentLon: null,
        directionId: null,
        endStub: null,
        polygon: '',
        polygonType: null,
        rectangleId: '',
        roadId: '',
        startStub: null
      },
      type: [
        { id: 1, name: '矩形' },
        { id: 2, name: '多边形' },
        { id: 3, name: '点' }
      ],
      roadList: [
        { roadId: 20100714, name: '郧十高速' }
      ],
      dirList: [
        { directionId: 1, name: '上行' },
        { directionId: 2, name: '下行' }
      ],
      dialogVisible: false
    }
  },
  mounted () {
    this.mapDraw()
  },
  methods: {

    mapDraw () {
      this.map = new window.BMap.Map(this.$refs.container) // 创建Map实例
      this.map.centerAndZoom(new window.BMap.Point(112.210093, 31.063745), 8) // 112.210093, 31.063745
      this.map.enableScrollWheelZoom()
      this.map.setMinZoom(3)
      this.map.setMaxZoom(20)
      var styleJson = [
        {
          featureType: 'water',
          elementType: 'all',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'land',
          elementType: 'all',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'boundary',
          elementType: 'geometry',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'railway',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'highway',
          elementType: 'geometry',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'highway',
          elementType: 'geometry.fill',
          stylers: {
            color: 'transparent',
            lightness: 0.1
          }
        },
        {
          featureType: 'highway',
          elementType: 'labels',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'arterial',
          elementType: 'geometry',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'arterial',
          elementType: 'geometry.fill',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'poi',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'green',
          elementType: 'all',
          stylers: {
            color: 'transparent',
            visibility: 'off'
          }
        },
        {
          featureType: 'subway',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'manmade',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'local',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'arterial',
          elementType: 'labels',
          stylers: {
            visibility: 'off'
          }
        },
        {
          featureType: 'boundary',
          elementType: 'geometry.fill',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'building',
          elementType: 'all',
          stylers: {
            color: 'transparent'
          }
        },
        {
          featureType: 'label',
          elementType: 'all',
          stylers: {
            visibility: 'off'
          }
        }
      ]
      this.map.setMapStyle({ styleJson: styleJson })
      this.getBoundary(this.map)
      var overlays = []
      var styleOptions = {
        strokeColor: 'blue', // 边线颜色。
        // fillColor: 'blue', // 填充颜色。当参数为空时，圆形将没有填充效果。
        strokeWeight: 3, // 边线的宽度，以像素为单位。
        strokeOpacity: 0.8, // 边线透明度，取值范围0 - 1。
        fillOpacity: 0.6, // 填充的透明度，取值范围0 - 1。
        strokeStyle: 'solid' // 边线的样式，solid或dashed。
      }
      // 实例化鼠标绘制工具
      var drawingManager = new window.BMapLib.DrawingManager(this.map, {
        isOpen: false, // 是否开启绘制模式
        enableDrawingTool: true, // 是否显示工具栏
        drawingToolOptions: {
          anchor: window.BMAP_ANCHOR_TOP_RIGHT, // 位置
          offset: new window.BMap.Size(5, 5) // 偏离值
        },
        circleOptions: styleOptions, // 圆的样式
        polylineOptions: styleOptions, // 线的样式
        polygonOptions: styleOptions, // 多边形的样式
        rectangleOptions: styleOptions // 矩形的样式
      })

      // 添加鼠标绘制工具监听事件，用于获取绘制结果
      drawingManager.addEventListener('overlaycomplete', e => {
        overlays.push(e.overlay)
        this.drawPoint.currentLat = e.overlay.point.lat
        this.drawPoint.currentLon = e.overlay.point.lng
        this.drawPoint.polygon = e.overlay.point.lat + ',' + e.overlay.point.lng
        this.dialogVisible = true
      })
      this.map.addEventListener('mousemove', e => {
        this.lng = e.point.lng
        this.lat = e.point.lat
      })
    },
    openDistanceTool () {
      var myDis = new window.BMapLib.DistanceTool(this.map)
      myDis.open()
    },
    getBoundary (map) {
      var bdary = new window.BMap.Boundary()
      bdary.get('湖北省', rs => {
        // 获取行政区域
        // map.clearOverlays() // 清除地图覆盖物
        var count = rs.boundaries.length // 行政区域的点有多少个
        if (count === 0) {
          // alert('未能获取当前输入行政区域')
          return
        }
        var pointArray = []

        for (var i = 0; i < count; i++) {
          var ply = new window.BMap.Polygon(rs.boundaries[i], {
            strokeWeight: 5,
            strokeColor: '#056197',
            fillColor: 'transparent'
          }) // 建立多边形覆盖物transparent a
          ply.disableMassClear()
          map.addOverlay(ply) // 添加覆盖物
          pointArray = pointArray.concat(ply.getPath())
        }
        //  map.setViewport(pointArray) // 调整视野

        map.addEventListener('zoomend', function (e) {
          var ZoomNum = map.getZoom()
          console.log(ZoomNum)
        })

        map.enableAutoResize()
        this.initData()
        // this.test(map)
      })
    },
    initData () {
      this.getLine('1', '20100714')
      this.getLine2('2', '20100714')
    },
    getLine2 (directionId, roadId) {
      getLatlonList({ directionId: directionId, roadId: roadId }).then(res => {
        var result = res.data == null ? [] : res.data
        if (result.length > 0) {
          var list = []
          var rs = []
          for (var i = 0; i < result.length; i++) {
            var temp = { lng: result[i].currentLon, lat: result[i].currentLat }
            if (rs.length !== 0 && result[i].startStub !== result[i - 1].endStub) {
              list.push(rs)
              rs = []
            }
            rs.push(temp)
          }
          list.push(rs)
          for (var z = 0; z < list.length; z++) {
            this.drawGreenLine(list[z])
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    getLine (directionId, roadId) {
      getLatlonList({ directionId: directionId, roadId: roadId }).then(res => {
        var result = res.data == null ? [] : res.data
        if (result.length > 0) {
          var list = []
          var rs = []
          for (var i = 0; i < result.length; i++) {
            var temp = { lng: result[i].currentLon, lat: result[i].currentLat }
            if (rs.length !== 0 && result[i].startStub !== result[i - 1].endStub) {
              list.push(rs)
              rs = []
            }
            rs.push(temp)
          }
          list.push(rs)
          for (var z = 0; z < list.length; z++) {
            this.drawGreenLine(list[z])
          }
        }
      }).catch(error => {
        console.log(error)
      })
    },
    drawGreenLine (list) {
      for (var i = 0; i < list.length - 1; i++) {
        var polyline = new window.BMap.Polyline([
          new window.BMap.Point(list[i].lng, list[i].lat), // 起始点的经纬度
          new window.BMap.Point(list[i + 1].lng, list[i + 1].lat)// 终点的经纬度
        ],
        {
          strokeColor: 'red', // 设置颜色
          strokeWeight: 5, // 宽度
          strokeOpacity: 1
        }
        )// 透明度

        this.map.addOverlay(polyline)
      }
    },
    handleDialogConfirm () {
      getLatlonSave(this.drawPoint).then(res => {
        if (res.code === 1400) {
          this.$message({
            message: '该数据已经存在！',
            type: 'error'
          })
          this.dialogVisible = false
        }
        if (res.code === 0) {
          this.dialogVisible = false
          this.$message.success('添加成功')
        }
      })
    },
    test (map) {
      var point = new window.BMap.Point(114.310436, 30.598218)
      var marker = new window.BMap.Marker(point) // 创建标注
      map.addOverlay(marker)
      var opts = {
        position: point, // 指定文本标注所在的地理位置
        offset: new window.BMap.Size(0, -0) // 设置文本偏移量
      }
      var label = new window.BMap.Label('武汉', opts) // 创建文本标注对象
      label.setStyle({
        /*  color: '#fff',
            fontSize: '12px',
            height: '20px',
            lineHeight: '20px',
            fontFamily: '微软雅黑' */
      })
      map.addOverlay(label)

      var list = [
        { Long: 113.755673, Lat: 30.43459 },
        { Long: 116.756823, Lat: 30.434559 },
        { Long: 113.757847, Lat: 30.434497 },
        { Long: 116.757973, Lat: 30.434543 }
      ]
      // var listLast = list.length - 1
      for (var j = 0; j < list.length - 1; j++) {
        drawGreenLine(j)
      }
      function drawGreenLine (i) {
        var polyline = new window.BMap.Polyline(
          [
            new window.BMap.Point(list[i].Long, list[i].Lat), // 起始点的经纬度
            new window.BMap.Point(list[i + 1].Long, list[i + 1].Lat) // 终点的经纬度
          ],
          {
            strokeColor: 'red', // 设置颜色
            strokeWeight: 10, // 宽度
            strokeOpacity: 1
          }
        ) // 透明度
        map.addOverlay(polyline)
      }
    }
  }
}
</script>
<style lang="less" scoped>
#container {
  height: 100%;
}
canvas {
  width: auto !important;
  max-width: none !important;
}
.tool-button {
  top: 200px;
  left: 500px;
  position: absolute;
  z-index: 99;
}
</style>
